const fs = require('fs');
const path = require('path');
const businessModulesDir = path.join(process.cwd(), 'src', 'modules', 'businessModule');
const commonModulesDir = path.join(process.cwd(), 'src', 'modules', 'commonModule');

const generateImportsAndExports = (baseDir, moduleType) => {
  const directories = fs
    .readdirSync(baseDir)
    .filter((name) => fs.lstatSync(path.join(baseDir, name)).isDirectory());
  const imports = [];
  const entities = [];
  directories.forEach((dir) => {
    const entityPath = path.join(baseDir, dir, 'assets');
    if (fs.existsSync(entityPath)) {
      const entityFiles = fs.readdirSync(entityPath).filter((file) => file.endsWith('.entity.ts'));
      entityFiles.forEach((file) => {
        const entityName = file.replace('.entity.ts', '');
        const moduleName = entityName.charAt(0).toUpperCase() + entityName.slice(1);
        const importPath = `@/modules/${moduleType}/${dir}/assets/${entityName}.entity`;
        imports.push(`import { ${moduleName} } from '${importPath}';`);
        entities.push(moduleName);
      });
    }
  });
  return { imports, entities };
};

export async function generateEntityImports() {
  const businessModules = generateImportsAndExports(businessModulesDir, 'businessModule');
  const commonModules = generateImportsAndExports(commonModulesDir, 'commonModule');
  const imports = [...businessModules.imports, ...commonModules.imports];
  const entities = [...businessModules.entities, ...commonModules.entities];
  const importStatements = imports.join('\n');
  const entitiesArray = entities.join(',\n  ');
  const combinedCode = `${importStatements}

/**
 * 导入的实体模块
 * 包含所有数据库实体的导入，用于在应用程序中注册和使用这些实体。
 * 每个实体代表数据库中的一张表，并包含表的结构和关系。
 */
export const Entities = [
  ${entitiesArray},
];
`;
  const outputFilePath = path.join(process.cwd(), 'src', 'modules', 'entities.ts');
  await fs.writeFileSync(outputFilePath, combinedCode, 'utf8');
  console.log('模块映射代码生成成功:', outputFilePath);
}
